package com.wendy.thirdpartyaccess.wechat;

import com.alibaba.fastjson.JSONObject;
import com.wendy.redis.RedisService;
import com.wendy.thirdpartyaccess.SocialConstants;
import com.wendy.utils.HttpClientUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author zhuwending
 */
@Slf4j
@Component
public class AccessToken {

    @Autowired
    private RedisService redisService;

    public String getAccessToken() {
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" +
                SocialConstants.APP_ID + "&secret=" + SocialConstants.APP_SECRET;
        if (redisService.exists("accessToken")) {
            return (String) redisService.get("accessToken");
        }
        JSONObject jsonObject = HttpClientUtils.httpGet(url);
        String errcode = "errcode";
        if (jsonObject.containsKey(errcode)) {
            log.error(jsonObject.getString("errmsg"));
            throw new RuntimeException("获取access_token异常");
        }
        String accessToken = jsonObject.getString("access_token");
        redisService.set("accessToken", accessToken, 7200L);
        return accessToken;
    }

    public JSONObject getTicket() {
        String url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + getAccessToken();
        JSONObject params = new JSONObject();
        params.put("expire_seconds", 604800);
        params.put("action_name", "QR_SCENE");
        JSONObject scene = new JSONObject();
        scene.put("scene_id", System.currentTimeMillis());
        params.put("action_info", scene);
        JSONObject result = HttpClientUtils.httpPost(url, params);
        String errcode = "errcode";
        if (result.containsKey(errcode)) {
            log.error(result.getString("errmsg"));
            throw new RuntimeException("获取ticket异常");
        }
        result.put("url", "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=");
        return result;
    }
}
